<template>
  <div  style="padding:15px;">
    <el-row>
      <el-col :span="12">
        <div>
          <el-tree
            ref="tree"
            :props="props"
            :data="treeData"
            node-key="value"
            :expand-on-click-node="false"
            default-expand-all
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  circle
                  @click="() => edit(data)"
                ></el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-plus"
                  circle
                  @click="() => append(data)"
                ></el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-minus"
                  circle
                  @click="() => remove(node, data)"
                ></el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="12">
        <div style="padding: 10px;">
          <el-form ref="form" :rules="rules" :model="form" label-width="80px">
            <el-row>
              <el-col :span="24">
                <div class="grid-content bg-purple">
                  <el-form-item label="父类名称:" style="margin-right:15px">{{form.parentName}}</el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="grid-content bg-purple">
                  <el-form-item label="名称" prop="name" style="margin-right:15px">
                    <el-input v-model="form.name" placeholder="请输入名称"/>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="grid-content bg-purple">
                  <el-form-item label="编码" prop="code" style="margin-right:15px">
                    <el-input v-model="form.code" placeholder="请输入编码"/>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="grid-content bg-purple">
                  <el-form-item label="显示顺序" prop="sort" style="margin-right:15px">
                    <el-input type="number" v-model="form.sort" placeholder="请输入显示顺序"/>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="funcSubmit">确 定</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import Vue from 'vue';
  import 'xe-utils';
  import VXETable from 'vxe-table';
  import 'vxe-table/lib/index.css';
  import XEUtils from 'xe-utils';
  import VXEUtils from 'vxe-utils';

  Vue.use(VXETable, VXEUtils, XEUtils, {mounts: ['cookie']});
  import request from '@/utils/request';

  export default {
    name: 'goodsTypeList',
    components: {},
    data() {
      return {
        isReadOnly:false,//编码默认可写
        message: '',
        loading: false,
        tableData: [],
        modelAddFlag: false,
        modelEditFlag: false,
        modelDetailFlag: false,
        copy: false,
        treeData: [],
        props: {
          label: 'name',
          children: 'children',
          sort:'sort'
        },
        form: {
          id: '',
          code: '',
          parentName:'',

          name: '',
          level: '',
          parentCode: '',
          sort: '',
          oldCode:''
        },
        oldNodeVal:'',
        rules: {
          code: [
            {required: true, message: '请输入编码', trigger: 'blur'},
            {validator: this.validCode, trigger: 'blur'},

          ],
          name: [
            {required: true, message: '请输入名称', trigger: 'blur'},

          ],
          sort: [{required: true, message: '请输入显示顺序', trigger: 'blur'}]
        }
      };
    },
    created() {
      this.loadTreeData();
    },
    methods: {
      loadTreeData() {
        request({
          url: '/wms/goodsType',
          method: 'get'
        }).then(response => {
          this.treeData = response.data.list;
          console.log(this.treeData)
        });
      },
      validCode(rule, value, callback) {
          if(typeof value === "undefined" || value == null || value.trim() == ""){
              return false;
          }
        this.getByCode(value, data => {
          if (data && this.form.id != data.id) {
            callback(new Error('商品编码已存在！'));
          } else {
            callback();
          }
        });
      },
      getByCode(code, backFun) {
        request({
          url: '/wms/goodsType/' + code,
          method: 'get'
        }).then(response => {
          backFun(response.data);
        });
      },
      append(data) {
        this.$refs['form'].clearValidate();
        this.isReadOnly=false;
        this.oldNodeVal = '';
        let parentNode = this.$refs.tree.getNode(data.value);
        this.form = {
          id: '',
          code: '',
          name: '',
          level: parentNode.level + 1,
          parentName: data.name,
          parentCode: data.typeCode,
          sort: ''
        };
        if (data.children && data.children.length > 0) {
          let lastChild = data.children[data.children.length - 1];
          this.getByCode(lastChild.value, data => {
            this.form.sort = data.sort + 1;
          });
        } else {
          this.form.sort = 1;
        }
      },
      edit(data) {
        this.$refs['form'].clearValidate();
        this.isReadOnly=true;
        this.oldNodeVal = data.typeCode;
        this.getByCode(data.code, data => {
          this.form = data;
          let parentNode = this.$refs.tree.getNode(this.form.parentCode);
          console.log(parentNode)
          this.form.parentName = parentNode.name;
          this.form.oldCode = this.form.code
        });
      },
      remove(node, data) {
        this.$confirm('确认删除吗？')
          .then(_ => {
            request({
              url: `/wms/goodsType/delete`,
              method: 'delete',
              data: [{code: data.value,id:data.id}]
            }).then(response => {
              this.$message({message: response.msg, type: 'success'});
              const parent = node.parent;
              const children = parent.data.children || parent.data;
              const index = children.findIndex(d => d.value === data.value);
              children.splice(index, 1);
            });
          })
          .catch(_ => {});
      },
      funcSubmit() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            const data = this.form;
            let requestType = 'post';
            if (data.id) {
              requestType = 'put';
            }
            request({
              url: '/wms/goodsType/save',
              method: requestType,
              params: data
            }).then(response => {
              this.$message({message: response.msg, type: 'success'});
              const parent = this.$refs.tree.getNode(this.form.parentCode);
              if( !parent.data.children){
                  this.$set(parent.data, 'children', []);
              }
                let children= parent.data.children;
              let newNode = {value:this.form.code,label:this.form.name,sort:this.form.sort,spread:true};
              if(this.oldNodeVal!==''){
                let oldNode =  this.$refs.tree.getNode(this.oldNodeVal);
                if(oldNode.data.children){
                    newNode.children=oldNode.data.children;
                }
                oldNode.remove();
              }
              let index = children.findIndex(d => d.sort >= newNode.sort);
              index=index==-1?children.length:index;
              children.splice(index, 0,newNode);
            }).then(() => this.$refs['form'].resetFields());
          } else {
            return false;
          }
        });
      }
    }
  };
</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
